import { useEffect, useState } from 'react'
import styles from './index.module.less'
import { getSexIcon, getLvIcon } from '@/apps/bilibili/utils/GetUserInfoIcon'
import BorderlessInput from '@/apps/bilibili/components/BorderlessInput'
import { FormatNumber } from '@/utils/common'
import StatItem from '@/apps/bilibili/components/StatItem'
import VideoItem from '@/apps/bilibili/components/VideoItem'
import { useLocation, useNavigate } from 'react-router-dom'
import GetWBIParams from '@/apps/bilibili/utils/GetWBI'
import { ApiRequest, apis } from '@/service'

const {
  user: {
    getUserCenter,
    getMyCenter,
    getUserSpaceStat,
    getUserRelationStat,
    getUserSubmitVideos
  },
} = apis.BilibiliService

const UserHome = (props: any) => {
  const navigate = useNavigate()
  const mid = useLocation()?.state?.mid || (JSON.parse(localStorage.getItem('loginInfo') || '{}')).mid
  const [userInfo, setUserInfo] = useState<any>([{}])
  const [userStat, setUserStat] = useState<any>([])
  const [submitVideoList, setSubmitVideoList] = useState<any>([])

  const [sign, setSign] = useState<string>('')

  useEffect(() => {
    let _userInfo = {
      "mid": 8220922,
      "name": "碧诗",
      "sex": "男",
      "face": "https://i2.hdslb.com/bfs/face/ef0457addb24141e15dfac6fbf45293ccf1e32ab.jpg",
      "face_nft": 0,
      "face_nft_type": 0,
      "sign": "https://kami.im 直男过气网红 #  We Are Star Dust",
      "rank": 20000,
      "level": 6,
      "jointime": 0,
      "moral": 0,
      "silence": 0,
      "coins": 0,
      "fans_badge": true,
      "fans_medal": {
        "show": true,
        "wear": true,
        "medal": {
          "uid": 2,
          "target_id": 335115,
          "medal_id": 45408,
          "level": 21,
          "medal_name": "伍千万",
          "medal_color": 1725515,
          "intimacy": 1980,
          "next_intimacy": 2000,
          "day_limit": 250000,
          "medal_color_start": 1725515,
          "medal_color_end": 5414290,
          "medal_color_border": 1725515,
          "is_lighted": 1,
          "light_status": 1,
          "wearing_status": 1,
          "score": 50001980
        }
      },
      "official": {
        "role": 2,
        "title": "bilibili创始人（站长）",
        "desc": "",
        "type": 0
      },
      "vip": {
        "type": 2,
        "status": 1,
        "due_date": 3931344000000,
        "vip_pay_type": 0,
        "theme_type": 0,
        "label": {
          "path": "",
          "text": "十年大会员",
          "label_theme": "ten_annual_vip",
          "text_color": "#FFFFFF",
          "bg_style": 1,
          "bg_color": "#FB7299",
          "border_color": "",
          "use_img_label": true,
          "img_label_uri_hans": "https://i0.hdslb.com/bfs/activity-plat/static/20220608/e369244d0b14644f5e1a06431e22a4d5/wltavwHAkL.gif",
          "img_label_uri_hant": "",
          "img_label_uri_hans_static": "https://i0.hdslb.com/bfs/vip/802418ff03911645648b63aa193ba67997b5a0bc.png",
          "img_label_uri_hant_static": "https://i0.hdslb.com/bfs/activity-plat/static/20220614/e369244d0b14644f5e1a06431e22a4d5/8u7iRTPE7N.png"
        },
        "avatar_subscript": 1,
        "nickname_color": "#FB7299",
        "role": 7,
        "avatar_subscript_url": "",
        "tv_vip_status": 1,
        "tv_vip_pay_type": 0,
        "tv_due_date": 2000822400
      },
      "pendant": {
        "pid": 32257,
        "name": "EveOneCat2",
        "image": "https://i2.hdslb.com/bfs/garb/item/488870931b1bba66da36d22848f0720480d3d79a.png",
        "expire": 0,
        "image_enhance": "https://i2.hdslb.com/bfs/garb/item/5974f17f9d96a88bafba2f6d18d647a486e88312.webp",
        "image_enhance_frame": "https://i2.hdslb.com/bfs/garb/item/4316a3910bb0bd6f2f1c267a3e9187f0b9fe5bd0.png"
      },
      "nameplate": {
        "nid": 10,
        "name": "见习偶像",
        "image": "https://i2.hdslb.com/bfs/face/e93dd9edfa7b9e18bf46fd8d71862327a2350923.png",
        "image_small": "https://i2.hdslb.com/bfs/face/275b468b043ec246737ab8580a2075bee0b1263b.png",
        "level": "普通勋章",
        "condition": "所有自制视频总播放数>=10万"
      },
      "user_honour_info": {
        "mid": 0,
        "colour": null,
        "tags": []
      },
      "is_followed": true,
      "top_photo": "http://i2.hdslb.com/bfs/space/cb1c3ef50e22b6096fde67febe863494caefebad.png",
      "theme": {},
      "sys_notice": {},
      "live_room": {
        "roomStatus": 1,
        "liveStatus": 0,
        "url": "https://live.bilibili.com/1024?broadcast_type=0&is_room_feed=0",
        "title": "试图恰鸡",
        "cover": "http://i0.hdslb.com/bfs/live/new_room_cover/96ee5bfd0279a0f18b190340334f43f473038288.jpg",
        "roomid": 1024,
        "roundStatus": 0,
        "broadcast_type": 0,
        "watched_show": {
          "switch": true,
          "num": 19,
          "text_small": "19",
          "text_large": "19人看过",
          "icon": "https://i0.hdslb.com/bfs/live/a725a9e61242ef44d764ac911691a7ce07f36c1d.png",
          "icon_location": "",
          "icon_web": "https://i0.hdslb.com/bfs/live/8d9d0f33ef8bf6f308742752d13dd0df731df19c.png"
        }
      },
      "birthday": "09-19",
      "school": {
        "name": ""
      },
      "profession": {
        "name": "",
        "department": "",
        "title": "",
        "is_show": 0
      },
      "tags": null,
      "series": {
        "user_upgrade_status": 3,
        "show_upgrade_window": false
      },
      "is_senior_member": 0,
      "mcn_info": null,
      "gaia_res_type": 0,
      "gaia_data": null,
      "is_risk": false,
      "elec": {
        "show_info": {
          "show": true,
          "state": 1,
          "title": "",
          "icon": "",
          "jump_url": "?oid=2"
        }
      },
      "contract": {
        "is_display": false,
        "is_follow_display": false
      }
    }
    //获取用户空间详细信息
    if (mid) {
      getUserCenterFnc()
    } else {
      getMyCenterFnc()
    }
    setUserInfo(_userInfo)
    // setSign(_userInfo.sign)
    //用户状态数
    let _userStat = {
      "archive": {
        "view": 213567370
      },
      "article": {
        "view": 3230808
      },
      "likes": 20295095
    }
    //关系状态数
    let _relateStat = {
      "mid": 332704117,
      "following": 32,
      "whisper": 0,
      "black": 0,
      "follower": 919515
    }
    getUserRelationStatFnc()
    getUserSpaceStatFnc()
    //需要的状态
    const stat = [{
      value: FormatNumber(_relateStat.following),
      label: '关注数'
    }, {
      value: FormatNumber(_relateStat.follower),
      label: '粉丝数'
    }, {
      value: FormatNumber(_userStat.likes),
      label: '获赞数'
    }, {
      value: FormatNumber(_userStat.archive?.view),
      label: '播放数'
    }]
    // setUserStat(stat)
    //查询用户投稿视频明细
    let _submitVideoList = {
      "list": {
        "tlist": {
          "1": {
            "tid": 1,
            "count": 26,
            "name": "动画"
          },
          "160": {
            "tid": 160,
            "count": 42,
            "name": "生活"
          },
          "211": {
            "tid": 211,
            "count": 3,
            "name": "美食"
          },
          "3": {
            "tid": 3,
            "count": 33,
            "name": "音乐"
          },
          "4": {
            "tid": 4,
            "count": 72,
            "name": "游戏"
          }
        },
        "vlist": [
          {
            "comment": 3558,
            "typeid": 47,
            "play": 1275661,
            "pic": "//i2.hdslb.com/bfs/archive/90157806a34646ac2d4c6af3e8b6156cb3460d14.jpg",
            "subtitle": "",
            "description": "第一期：BV1ak4y1B7aG\n第二期：BV1eA411Y7FN\n脚本/绘画/配音/动画/片尾曲：warma\n第三期终于做完啦！这是一个以我平时发呆的时候想到的一些灵感组成的冷笑话合集，名字叫《沃玛的生活》，可以当作日常搞笑单元小动画来看。\n如果你喜欢这个系列的话请点赞投币收藏一键三连给我一些继续制作的动力吧，我真的非常非常需要更多的动力！\n祝看得开心~\n我的微博：@_warma_",
            "copyright": "",
            "title": "【warma】沃玛的新番更新！从现在开始放飞自我【沃玛的生活/第三期】",
            "review": 0,
            "author": "Warma",
            "mid": 53456,
            "created": 1605844817,
            "length": "05:16",
            "video_review": 7470,
            "aid": 585275804,
            "bvid": "BV1sz4y1y7KJ",
            "hide_click": false,
            "is_pay": 0,
            "is_union_video": 0,
            "is_steins_gate": 0
          },
          {
            "comment": 2979,
            "typeid": 21,
            "play": 840676,
            "pic": "//i2.hdslb.com/bfs/archive/b43f88c6ebae8fdc7dfb663f6f6f2931b924c763.jpg",
            "subtitle": "",
            "description": "前一阵子过生日，大家的礼物经过几番转寄终于收到了~于是录了这期礼物开箱视频。\n现在也在感慨，大家的礼物真的都太强了，居然这些全都是手工做的，真的好厉害！\n这些手工礼物背后得花多少时间和心力啊……这些对我来说都是无价的礼物，制作礼物的大家真的有心了，谢谢！！\n收到这些礼物真的很开心，视频的封面也是在这样激动的情况下画出来的，祝你看得开心~\n我的微博：@_warma_",
            "copyright": "",
            "title": "【warma】来开箱！大家寄来的生日礼物",
            "review": 0,
            "author": "Warma",
            "mid": 53456,
            "created": 1604635221,
            "length": "24:28",
            "video_review": 10476,
            "aid": 287744380,
            "bvid": "BV1xf4y1q7XN",
            "hide_click": false,
            "is_pay": 0,
            "is_union_video": 0,
            "is_steins_gate": 0
          }
        ]
      },
      "page": {
        "pn": 1,
        "ps": 2,
        "count": 176
      },
      "episodic_button": {
        "text": "播放全部",
        "uri": "//www.bilibili.com/medialist/play/53456?from=space"
      }
    }
    // TODO:通过视频id获取视频基本信息
    setSubmitVideoList(_submitVideoList.list.vlist)
    // getUserSubmitVideosFnc()
  }, [])

  useEffect(() => {
    console.log('userStat', userStat)
  }, [userStat])

  const getUserCenterFnc = () => {
    const params = GetWBIParams({
      mid: mid,
      wts: Date.now(), // 当前时间戳
    })
    ApiRequest({ api: getUserCenter, params }).then((res: any) => {
      console.log('params', params)
      console.log('getUserCenter', res)
      setUserInfo(res.data)
    })
  }

  const getMyCenterFnc = () => {
    ApiRequest({ api: getMyCenter }).then((res: any) => {
      console.log('getMyCenter', res)
      setUserInfo(res.data)
    })
  }

  const getUserRelationStatFnc = () => {
    const params = {
      vmid: mid,
    }
    ApiRequest({ api: getUserRelationStat, params }).then((res: any) => {
      console.log('getUserRelationStatFnc', res)
      if (res.data) {
        let following = {
          value: FormatNumber(res.data.following) || 0,
          label: '关注数'
        }
        let follower = {
          value: FormatNumber(res.data.follower) || 0,
          label: '粉丝数'
        }
        let _data = userStat
        _data.push(following)
        _data.push(follower)
        setUserStat(_data)
      }
    })
  }

  const getUserSpaceStatFnc = () => {
    const params = {
      mid,
    }
    ApiRequest({ api: getUserSpaceStat, params }).then((res: any) => {
      console.log('getUserSpaceStatFnc', res)
      if (res.data) {
        let likes = {
          value: FormatNumber(res.data.likes) || 0,
          label: '获赞数'
        }
        let view = {
          value: FormatNumber(res.data.archive?.view) || 0,
          label: '播放数'
        }
        let _data = userStat
        _data.push(likes)
        _data.push(view)
        setUserStat(_data)
      }
    })
  }

  const getUserSubmitVideosFnc = () => {
    const params = {
      mid,
    }
    ApiRequest({ api: getUserSubmitVideos, params }).then((res: any) => {
      setSubmitVideoList(res.data.list?.vlist)
    })
  }

  const onSignInputChange = (value: string) => {
    // console.log(value)
    setSign(value)
  }

  const onSignSubmit = () => {
    console.log(sign)
    // TODO：请求修改签名value
  }

  const onVideoClick = (item: any) => {
    //TODO跳转播放视频
    navigate('/aio/bilibili/play', {
      state: {
        aid: item.aid,
      }
    })
  }

  const onAuthorClick = (item: any) => {
    //TODO跳转到作者主页
    navigate('/aio/bilibili/user', {
      state: {
        mid: item.owner?.mid
      }
    })
  }

  const renderVideoListByTitle = (title: string, list: Array<any>) => {
    return <div className={styles.titleList}>
      <div className={styles.blockTitle}>{title}</div>
      <div className={styles.titleVideoList}>
        {list?.map((item: any, index: number) => {
          return <VideoItem videoItem={item} direction={'vertical'} key={index} onAuthorClick={onAuthorClick} onVideoClick={onVideoClick} />
        })}
      </div>
    </div>
  }

  const onStatClick = (label: string) => {
    //TODO：跳转关注/粉丝
    if (label.includes('关注')) {
      console.log('关注')
    } else if (label.includes('粉丝')) {
      console.log('粉丝')
    }
  }


  return <div className={styles.personalCenter}>
    <div className={styles.backgroundBoard}>
      <img src={userInfo?.top_photo} style={{ width: '100%' }} alt="无法显示" />
      <div className={styles.userItem}>
        <div className={styles.avatarWrapper}>
          <img className={styles.avatar} src={userInfo?.face} alt="暂时无法显示" />
        </div>
        <div className={styles.userDesc}>
          <div className={styles.upName}>
            <div className={styles.name}>{userInfo?.name}</div>
            <div>{getSexIcon(userInfo?.sex)}</div>
            <div>{getLvIcon(userInfo?.level)}</div>
          </div>
          <BorderlessInput
            // value={userInfo.sign ? userInfo.sign : '编辑个性签名'}
            value={sign ? sign : '编辑个性签名'}
            onChange={onSignInputChange}
            onSubmit={onSignSubmit}
          />
        </div>
        <div className={styles.userStat}>
          {userStat?.map((item: any, index: number) => {
            return <StatItem frontValue={item.label} backValue={item.value} key={index} className={`${styles.statItem} ${styles['state' + index]}`} onClick={onStatClick} />
          })}
        </div>
      </div>
    </div>
    {renderVideoListByTitle('投稿的视频', submitVideoList)}
    {renderVideoListByTitle('收藏的视频', submitVideoList)}
    {renderVideoListByTitle('历史记录', submitVideoList)}

  </div >
}

export default UserHome
